package main

import (
	"context"
	"fmt"
	"time"
)

func main04() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
	defer cancel()

	timer := time.NewTimer(time.Second * 2)
	for {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err())
			return
		case <-timer.C:
			fmt.Println("timer start")
			time.Sleep(time.Second * 2)
			fmt.Println("timer end")
			return
		}
	}
}

func main05() {
	stop := make(chan struct{}, 0)

	go func() {
		i := 0
		for {
			time.Sleep(time.Second)
			i++
			if i >= 3 {
				fmt.Println("i = ", i)
				stop <- struct{}{}
			}
		}
	}()

	go func() {
		fmt.Println("main logic start")
		time.Sleep(time.Second * 10)
		fmt.Println("main logic end")
	}()

	<-stop
	fmt.Println("main end")
}

func main() {
	stop := make(chan struct{}, 0)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()

	go func() {
		for {
			select {
			case <-ctx.Done():
				fmt.Println(ctx.Err())
				stop <- struct{}{}
			}
		}
	}()

	go func() {
		fmt.Println("main logic start")
		time.Sleep(time.Second * 10)
		fmt.Println("main logic end")
	}()

	<-stop
	fmt.Println("main end")
}
